import React, { Component, Fragment } from 'react'
import { PlusOutlined, ExclamationCircleFilled } from '@ant-design/icons'
import Cookies from 'js-cookie'
import {
  Modal, message, Dropdown, Menu, Tooltip, Spin,
  // Empty
} from 'antd'
import moment from 'moment'

import request from '@/Utils/fecth'
import { address } from '@/Utils/apiConfig'
import {
  // orgObj,
  STATUS,
} from '@/Utils/CONST'
import { CREATECONSORTIUM } from '@/Utils/socketName'
import Event from '@/Utils/Event'
import { checkPermission } from '@/components/AuthComponent/utils'

const { leagueListData, deleteLeague } = address.fabric
const { operaAuth, instancesCancel } = address.bdpApi
const { renewLink, projectEnv } = address

export default class Consortium extends Component {
  constructor(props) {
    super(props)
    this.state = {
      allList: [],
      showList: [],
      showAll: false,
      exitIdArr: [], // 退订中实例id
      loading: false,
    }
  }

  componentDidMount() {
    this.getLeagueData()
    Event.on(CREATECONSORTIUM, this.getLeagueData)
  }

  componentWillUnmount() {
    Event.off(CREATECONSORTIUM, this.getLeagueData)
  }

  getLeagueData = async() => {
    this.setState({
      loading: true,
    })
    const res = await request().get(leagueListData)
    this.setState({
      loading: false,
    })
    if (res && res.status === 200) {
      this.setState({
        allList: res.data,
        showList: res.data.slice(0, 3),
      })
    }
  }

  // 删除当前选择联盟
  deleteCurrentLeague = (e, item) => {
    e.stopPropagation()
    const uploadLeagueData = (id) => {
      let data = this.state.allList
      let index = -1
      for (let i = 0, len = data.length; i < len; i++) {
        let legItem = data[i]
        if (legItem.id === id) {
          index = i
          break
        }
      }
      if (index !== -1) {
        data.splice(index, 1)
      }
      this.setState({
        allList: data,
        showList: data.slice(0, 3),
      })
    }
    confirm({
      title: '删除联盟',
      className: 'common-confirm-small',
      icon: <ExclamationCircleFilled />,
      getContainer: () => this.props.container,
      content: `确定要删除“${item.display_name}”？删除后，在概览也将不再可见！`,
      onOk() {
        request().delete(deleteLeague.format({ consortiumId: item.id })).then(res => {
          if (res && res.status === 200) {
            uploadLeagueData(item.id)
            message.success('删除联盟成功')
          }
        })
      },
    })
  }

  changeLeagueShow = () => {
    const { showAll } = this.state
    this.setState({
      showAll: !showAll,
    })
  }

  // 联盟详情
  goToDetail = (item, canClick) => {
    if (!canClick) {
      return false
    }
    const id = item.id
    const name = item.display_name || '无'
    // 存储联盟的name，用于面包屑展示
    Cookies.set('league', name)
    this.props.history.push({
      pathname: `/dashboard/fabric/leagueInfo/${id}/${name}`,
    })
  }

  operateMenuClick = (code, item, { key, domEvent }) => {
    domEvent.stopPropagation()
    const name = item.display_name
    const id = item.id
    const currentTime = new Date().getTime()
    const createTime = new Date(item.createTime).getTime()
    const mins = (currentTime - createTime) / (60 * 1000) // 相差的分钟数
    let operate = key === '0' ? '退订' : '续订'
    if (mins < 30) {
      return Modal.info({
        title: `该实例不可${operate}`,
        icon: <ExclamationCircleFilled />,
        className: 'common-info common-info-small',
        getContainer: () => this.props.container,
        content: `订购30分钟后可进行${operate}`,
      })
    }
    // 暂停无法操作
    if (item.status === 'STOP') {
      return Modal.info({
        title: `该实例不可${operate}`,
        icon: <ExclamationCircleFilled />,
        className: 'common-info common-info-small',
        getContainer: () => this.props.container,
        content: `当前实例已处于暂停状态，不可${operate}`,
      })
    }
    if (code !== 'yes') {
      const obj = {
        '1': `当前实例在创建中，不可${operate}`,
        '2': `当前组织在添加至联盟，不可退订`,
        '3': `当前实例运行错误，不可${operate}`,
        '4': `初始Orderer组织不支持${operate}操作`,
        '5': `当前组织在添加至联盟，不可${operate}`,
        '6': `当前组织在添加至联盟，不可${operate}`,
        '7': `当前实例在退订中，不可${operate}`,
        '8': `当前实例在退订中，不可${operate}`,
      }
      return Modal.info({
        title: `该实例不可${operate}`,
        icon: <ExclamationCircleFilled />,
        className: 'common-info common-info-small',
        getContainer: () => this.props.container,
        content: obj[code],
      })
    } else {
      // 实例退订
      key === '0' && this.cancelOperate(id, name)
      // 续订
      key === '1' && this.renewFn(id)
    }
  }

  // 实例退订
  cancelOperate = async(id, name) => {
    Modal.confirm({
      title: '是否退订该实例？',
      className: 'common-confirm-small',
      icon: <ExclamationCircleFilled />,
      getContainer: () => this.props.container,
      content: `实例${name}退订后不能恢复，退订后账户不再对该实例计费`,
      onOk: async() => {
        // 实例退订中
        const { exitIdArr } = this.state
        exitIdArr.push(id)
        this.setState({
          exitIdArr,
        })
        const res1 = await request().get(`${operaAuth}?instanceId=${id}&operType=CANCEL`)
        if (res1 && res1.status === 200) {
          const code = res1.data.data.checkCode || ''
          if (code && code === '0' || code === '00') {
            const res2 = await request().post(`${instancesCancel}?instanceId=${id}`)
            if (res2 && res2.status === 200) {
              message.success(`实例${name}退订成功`)
              this.deleteExitItem(id)
              this.getLeagueData()
            } else {
              this.deleteExitItem(id)
              Modal.info({
                title: `退订失败`,
                icon: <ExclamationCircleFilled />,
                className: 'common-info common-info-large',
                getContainer: () => this.props.container,
                content: '退订失败，实例将继续产生费用。您可以联系客服完成实例退订。客服号码：4001100868',
              })
            }
          } else {
            this.deleteExitItem(id)
            message.warning(res1.data.data.checkMessage || '校验未通过')
          }
        } else {
          this.deleteExitItem(id)
          message.error('权限校验失败')
        }
      },
    })
  }

  // 实例续订
  renewFn = async(id) => {
    const res1 = await request().get(`${operaAuth}?instanceId=${id}&operType=RENEW`)
    if (res1 && res1.status === 200) {
      const code = res1.data.data.checkCode || ''
      if (code && code === '0' || code === '00') {
        this.goToLink(renewLink.format({ instanceId: id, regionId: this.props.RegionId.regionId }))
      } else {
        message.warning(res1.data.data.checkMessage || '续订校验未通过')
      }
    } else {
      message.error('续订权限校验失败')
    }
  }

  deleteExitItem = (id) => {
    // 取消退订中状态
    const { exitIdArr } = this.state
    exitIdArr.indexOf(id) >= 0 && exitIdArr.splice(exitIdArr.indexOf(id), 1)
    this.setState({
      exitIdArr,
    })
  }

  getOperation = (item, code) => {
    // 创建成功和失效状态支持退订，续订功能     被邀请用户不允许对联盟进行退订续订
    if (projectEnv === 'bcs' || !item.isCreator) {
      return false
    }
    const { userInfo } = this.props
    const userType = (userInfo && userInfo.userType) || 'ignore'
    // 时间过期
    if (userType === 'INTERNET_CUSTOMER' && moment(item.dueDate).valueOf() - Date.now() < 0) {
      return false
    }
    // 获取menu
    let arr = MENU[userType] || []
    const overlay = <Menu onClick={this.operateMenuClick.bind(this, code, item)}>
      {
        arr.map(item => {
          return (
            <Menu.Item key={item.key}>
              <span>{item.label}</span>
            </Menu.Item>
          )
        })
      }
    </Menu>
    return <Dropdown
      getPopupContainer={() => this.props.container}
      overlay={overlay}>
      <div className="operate" onClick={event => event.stopPropagation()}>
        <span></span>
        <span></span>
        <span></span>
      </div>
    </Dropdown>
  }

  // 删除当前选择联盟
  deleteCurrentLeague = (e, item) => {
    e.stopPropagation()
    const uploadLeagueData = (id) => {
      let data = this.state.allList
      let index = -1
      for (let i = 0, len = data.length; i < len; i++) {
        let legItem = data[i]
        if (legItem.id === id) {
          index = i
          break
        }
      }
      if (index !== -1) {
        data.splice(index, 1)
      }
      this.setState({
        allList: data,
        showList: data.slice(0, 3),
      })
    }
    confirm({
      title: '删除提示',
      className: 'common-confirm-small',
      icon: <ExclamationCircleFilled />,
      getContainer: () => this.props.container,
      content: `确定要删除“${item.display_name}”？删除后，在概览也将不再可见！`,
      onOk() {
        request().delete(deleteLeague.format({ consortiumId: item.id })).then(res => {
          if (res && res.status === 200) {
            uploadLeagueData(item.id)
            message.success('删除联盟成功')
          }
        })
      },
    })
  }

  goToLink = (link) => {
    this.props.history.push(link)
  }

  render() {
    const { allList, showList, showAll, exitIdArr, loading } = this.state
    const successLeagueList = (allList || []).filter(
      (v) => v.status === 'SUCCESS' || v.userConsortiumStatus === 'SUCCESS'
    )
    return <div className="Consortium">
      <Spin spinning={loading}>
        <div className="fabric-league fabric-title">
          <div className="flow-title">
            <span className="title-text">我的联盟</span>
          </div>
          <div className="league-group group">
            {
              !loading && (successLeagueList.length < 1 || process.env.REACT_APP_CONSORTIUM_COUNT === 'more') && checkPermission('fabric-league-create') &&
              <div className="create item league-item"
                onClick={() => this.goToLink('/dashboard/fabric/createLeague')}
              >
                <div className="league-plus plus">
                  <PlusOutlined />
                </div>
                <span>构建联盟</span>
              </div>
            }
            {
              (showAll ? allList : showList).map(item => {
                const statusType = item.status === 'STOP' ? 'status' : 'userConsortiumStatus' // 联盟冻结状态用status字段
                const item_status = item[statusType]
                // let code = exitIdArr.includes(item.id) ? '8' : (statusCode[item_status] || 'yes')
                // let _spec = orgObj.performance[item.spec || ''] || '标准版' // 联盟的产品规格
                // ADDED 和 SUCCESS 才可以点击
                let canClick = ((item_status === 'ADDED' || item_status === 'SUCCESS')) && !exitIdArr.includes(item.id) // 是否可以点击
                return (
                  <div
                    className={`item league-item ${canClick ? '' : 'disabled-click'} ${item.isGuomi ? 'isGuomi' : ''}`}
                    key={item.id}
                    onClick={() => this.goToDetail(item, canClick)}>
                    <div className="header">
                      <div className="status">
                        <Tooltip placement="top" title={(STATUS[item_status] || {}).tooltip || '创建失败'}>
                          <img alt="" src={(STATUS[item_status] || {}).icon || require('@/images/fabric/error.svg')} />
                        </Tooltip>
                      </div>
                      <div className="name-wrapper">
                        <div className="title-wrapper">
                          <div className={'name ellipsis'}>
                            {item.display_name || '无'}
                          </div>
                          {/* <div style={{ display: 'flex', alignItems: 'center' }}>
                            <div className={ _spec === '企业版' ? 'performance company_p' : 'basic_p performance'}>
                              {_spec}
                            </div>
                            {
                              this.getOperation(item, code)
                            }
                          </div> */}
                        </div>
                        <div className="org-address ellipsis" >{item.domain}</div>
                      </div>
                    </div>
                    {/* 去掉原本删除功能，新增苏研退订跳转链接 */}
                    {/* {
                      item.isCreator === 1 &&
                      <div className="delete-league">
                        <div onClick={(e) => this.deleteCurrentLeague(e, item)} className="show-delete">
                          <div className="delete-img" />
                        </div>
                      </div>
                    } */}
                    <div className="league-info info">
                      <div className="info-item">
                        <span>组织数</span>
                        <span className="info-value">{item.orgNum}</span>
                      </div>
                      <div className="info-item">
                        <span>通道数</span>
                        <span className="info-value">{item.channelNum}</span>
                      </div>
                      <div className="info-item" title={item.creator}>
                        <span>创建者</span>
                        <span className="info-value">{item.creator || '--'}</span>
                      </div>
                      <div className="info-item">
                        <div>创建时间</div>
                        <div className="info-value">
                          {(item.createTime &&
                          moment(item.createTime).format('YYYY.MM.DD')) ||
                          '--'}
                        </div>
                      </div>
                    </div>
                  </div>
                )
              })
            }
          </div>
          {/* {
            !allList.length &&
            <Empty style={{ padding: '40px 0 ', background: '#fff', margin: '0 0 10px 0' }} />
          } */}
          {
            allList && allList.length > 3 &&
          <div className="show-all-league show-all" onClick={this.changeLeagueShow}>
            {
              showAll ? <Fragment>
                显示部分联盟
                <div className="tringle-up"></div>
              </Fragment> : <Fragment>
                展开所有联盟
                <div className="tringle-down"></div>
              </Fragment>
            }
          </div>
          }
        </div>
      </Spin>

    </div>
  }
}

// 配置不同状态对应的文案
// const statusCode = {
//   'CREATING': '1',
//   'TOBE_ADDED': '2',
//   'FAIL': '3',
//   'FAILED': '3',
//   'PREPARE_BUILDING': '5',
//   'PREPARE_SUCCESS': '6',
//   'EXITING': '7',
// }

// 操作item
const MENU = {
  'INTERNET_CUSTOMER': [
    {
      label: '续订',
      key: '1',
    },
  ],
  'GOVERNMENT_CUSTOMER': [
    {
      label: '退订',
      key: '0',
    },
  ],
  'ignore': [
    {
      label: '续订',
      key: '1',
    },
    {
      label: '退订',
      key: '0',
    },
  ],
}
